package com.mql.onlinechatsystem.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mql.onlinechatsystem.system.entity.SysUser;
import com.mql.onlinechatsystem.system.entity.TbUserrelation;
import com.mql.onlinechatsystem.system.mapper.SysUserMapper;
import com.mql.onlinechatsystem.system.mapper.TbUserrelationMapper;
import com.mql.onlinechatsystem.system.service.ITbUserrelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mql.onlinechatsystem.system.vo.SysUserRelationVo;
import com.mql.onlinechatsystem.system.vo.TbUserrelationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 马庆林
 * @since 2023-03-08
 */
@Service
public class TbUserrelationServiceImpl extends ServiceImpl<TbUserrelationMapper, TbUserrelation> implements ITbUserrelationService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public List<SysUserRelationVo> getFriendRelation(String userid) {
        List<TbUserrelation> tbUserrelations = baseMapper.selectList(new QueryWrapper<TbUserrelation>(new TbUserrelation(), "relationlevel").eq("userid",userid).groupBy("relationlevel"));
        List<SysUserRelationVo> sysUserRelationVoList = tbUserrelations.stream().map(item -> {
            SysUserRelationVo sysUserRelationVo = new SysUserRelationVo();
            Integer relationlevel = item.getRelationlevel();
            sysUserRelationVo.setRelationlevel(relationlevel);
            List<TbUserrelation> tbUserrelationList = baseMapper.selectList(new QueryWrapper<TbUserrelation>().eq("userid",userid).eq("relationlevel", relationlevel));
            List<TbUserrelationVo> collect = tbUserrelationList.stream().map(TbUserrelation -> {
                TbUserrelationVo tbUserrelationVo = new TbUserrelationVo();
                BeanUtils.copyProperties(TbUserrelation, tbUserrelationVo);
                SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>(new SysUser(), "username").eq("userid", TbUserrelation.getFriendid()));
                tbUserrelationVo.setFriendname(sysUser.getUsername());
                return tbUserrelationVo;
            }).collect(Collectors.toList());
            sysUserRelationVo.setTbUserrelationList(collect);
            return sysUserRelationVo;
        }).collect(Collectors.toList());
        return sysUserRelationVoList;
    }
}
